import axios from "axios"
import querystring from "querystring"
import { RequestUrl } from "./staticName"
import utils from "./utils"
const { env } = require("../../package.json")
import store from "./store"
axios.defaults.withCredentials=false
let timeout = 1000*60*5
const Request = {
    post(mod, op, param) {
        if (typeof(param) == "undefined" || param == "" || param == null) {
            param = {};
        }
        let url =''
        if (mod=="login") {
            url = RequestUrl + mod
        }
        else if(mod=='logout'){
            url = RequestUrl  + mod
        }
        else{
            url = RequestUrl + mod + "/" + op;
            // param["token"] = sessionStorage.getItem("token");
            param["token"] = store.state.token
        }
        if ((process.env.NODE_ENV == "development" || env == "dev") && mod!="login") {
            url += "?_t=" + encodeURIComponent("298-1234567890");
        }
        param["currVer"] = utils.CurrVersion;
        return axios.post(url, querystring.stringify(param),{timeout: timeout}).then(function(response) {
            return Promise.resolve({ "code": 0, "data": response.data });
        }).catch(function(error) {
            try {
                if(error.code === 'ECONNABORTED' || error.message ===   "Network Error" ||  error.message.includes("timeout")){
                    utils.showTip(" 请求超时， 请稍后再试…");
                    return Promise.resolve({ "code": -403, "data": "请求超时， 请稍后再试…" });
                }
                utils.showTip(error.response.data);
                if (error.response.data == "not login" || error.response.data == "账户已禁用") {
                    setTimeout(function() {
                        store.commit("loginOut");
                        // window.location.href = RequestUrl + "logout";
                        // window.location.href = RequestUrl + "logout?t="+ new Date().getTime();
                        window.location.href = RequestUrl + "logout?t="+Math.floor(Math.random() * (10000000 - 0 + 1)) + 0
                    }, 1000)
                }
                return Promise.resolve({ "code": -403, "data": error.response.data });
            } catch (e) {
                console.log("e", e)
                utils.showTip("网络断了");
                return Promise.resolve({ "code": -403, "data": "网络断了" });
            }
        });
    }
}
export default Request;